package com.itheima.tlias84.controller;

import com.itheima.tlias84.annotation.Log;
import com.itheima.tlias84.controller.po.InsertClazzParam;
import com.itheima.tlias84.controller.po.SelectClazzPageParam;
import com.itheima.tlias84.dao.entity.Clazz;
import com.itheima.tlias84.service.ClazzService;
import com.itheima.tlias84.service.dto.SelectClazzDTO;
import com.itheima.tlias84.utils.ResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Objects;

@RestController
@RequestMapping("/clazzs")
public class ClazzController {

    @Autowired
    ClazzService clazzService;

    @GetMapping
    public ResultUtil selectClazzPage(SelectClazzPageParam param) {
        if (!Objects.isNull(param.getPage()) && !Objects.isNull(param.getPageSize())) {
            return clazzService.selectPage(param);
        } else {
            return ResultUtil.failure();
        }
    }

    @GetMapping(("/{id}"))
    public ResultUtil selectClazzById(@PathVariable Integer id) {
        SelectClazzDTO rs = clazzService.selectById(id);
        if (!Objects.isNull(rs)) {
            return ResultUtil.success(rs);
        } else {
            return ResultUtil.failure();
        }
    }

    @GetMapping("/list")
    public ResultUtil selectAllClazz() {
        List<Clazz> list = clazzService.selectAll();
        return ResultUtil.success(list);
    }

    @Log
    @PostMapping
    public ResultUtil insertClazz(@RequestBody InsertClazzParam param) {

        if (!Objects.isNull(param.getName()) && !Objects.isNull(param.getBeginDate())
                && !Objects.isNull(param.getEndDate()) && !Objects.isNull(param.getSubject())) {
            int i = clazzService.insertClazz(param);
            if (i == 1) {
                return ResultUtil.success(i);
            } else {
                return ResultUtil.failure();
            }
        } else {
            return ResultUtil.failure();
        }
    }

    @Log
    @DeleteMapping("/{id}")
    public ResultUtil deleteClazz(@PathVariable Integer id) {
        int flag = clazzService.deleteClazz(id);
        if (flag == 1) {
            return ResultUtil.success();
        } else {
            return ResultUtil.failure();
        }
    }

    @Log
    @PutMapping
    public ResultUtil updateClazz(@RequestBody InsertClazzParam param) {
        int flag = clazzService.updateClazzById(param);
        if (flag == 1) {
            return ResultUtil.success();
        }else if (flag == -1) {
            return ResultUtil.failure("班级名称已存在");
        }else {
            return ResultUtil.failure();
        }
    }
}
